class Buffer
   int[] buf;
   int first, last, n, i;

   public void init(int size) {
       buf=new int[size];
       n=size; i=0; first=0; last=0;
   }

   public synchronized void put(int x) {
      while (i<n) wait();
      buf[last]=x;
      last=(last+1)%n;
      i=i+1;
      notifyAll();
   }

   public synchronized int get() {
      int x;
      while (i==0) wait();
      x=buf[first];
      first=(first+1)%n;
      i=i-1;
      notifyAll();
      return x;
   }
}
